<!--下订单主页面-->
<template>
  <div class="contain">
    <app-header></app-header>
    <div class="form-wrap mb30">
      <div class="form-choice line" v-if="formDate.list3.length>0">
        <popup-picker class="vux-form-require" title="客户名称" :data="formDate.list3" :columns="3" v-model="formDate.value3" placeholder="点击选择" value-text-align="left" :show-name="formDate.customShow"></popup-picker>
      </div>
      <div class="form-wrap-row" v-if="formDate.list3.length==0">
        <div class="line cf" @click="noneCustoms">
          <div class="label f-l"><span class="red">*</span>客户名称</div>
          <i class="iconfont icon-more f-r"></i>
        </div>
      </div>
      <div class="form-wrap-row">
        <div class="line cf" @click="toAddress">
          <div class="label f-l">收货信息</div>
          <i class="iconfont icon-more f-r"></i>
        </div>
      </div>
      <div class="form-wrap-row">
        <p class="ft14 gray mb10">收货人：{{seleAddr.Contacts || '--'}}
          <em class="f-r mr20">{{seleAddr.ContactsTel}}</em>
        </p>
        <p class="ft14 gray">{{seleAddr.Province | province}}{{seleAddr.City | city}}{{seleAddr.District | district}}{{seleAddr.Address}}</p>
        <div id="address" style="display:none">{{seleAddr.Province | province}}/{{seleAddr.City | city}}/{{seleAddr.District | district}}</div>
      </div>
    </div>

    <!-- <div class="place-order-warp mb30">
      <h2 class="tit"><span class="red">*</span>选择下单方式</h2>
      <ul class="cf">
        <li class="place-order-li displayflex" @click="choiceWay(1)" :class="{cur:formDate.choiceGoods}">
          <i class="iconfont icon-drug"></i>
          <dl class="flex1">
            <dt class="ft17">商品下单</dt>
            <dd>自选商品
              <p>提交订单</p>
            </dd>
          </dl>
        </li>
        <li class="place-order-li displayflex" @click="choiceWay(-1)" :class="{cur:formDate.choiceQuick}">
          <i class="iconfont icon-logistics"></i>
          <dl class="flex1">
            <dt class="ft17">快速下单</dt>
            <dd>支持语音、照片、文本三种方式快速下单</dd>
          </dl>
        </li>
      </ul>
    </div> -->

    <div class="form-wrap mb30">
      <div class="form-wrap-row">
        <div class="line cf" @click="choiceWay(1)">
          <div class="label f-l">选择商品</div>
          <i class="iconfont icon-more f-r"></i>
        </div>
      </div>
      <div class="form-wrap-row" v-if="this.formDate.choiceGoods">
        <div class="line displayflex" @click="choicedlist">
          <div class="label">商品清单</div>
          <div class="ipt flex1">已选{{checkItem.length}}种商品</div>
          <i class="iconfont icon-more"></i>
        </div>
      </div>
    </div>
    <div class="form-wrap">
      <div class="form-wrap-row" v-if="this.formDate.choiceGoods">
        <div class="line displayflex">
          <div class="label">总金额</div>
          <div class="ipt flex1 org1">￥{{amount  | fmoney}}</div>
        </div>
      </div>
      <div class="form-wrap-row" v-if="this.formDate.choiceQuick">
        <div class="line displayflex">
          <div class="label">总金额</div> 
          <div class="ipt flex1"><input type="text" placeholder="点击输入" v-model="quickAmount"></div>
          <em class="unit">元</em>
        </div>
      </div>
      <div class="form-choice line">
        <datetime class="vux-form-require" v-model="formDate.arriveTime" 
          :show.sync="visibility"
          :start-date="today"
          title="要求到货日期" placeholder="点击选择"></datetime>
      </div>
    </div>
    <div class="mb30 choice-time" id="setDay">
      <label @change="setTimes(1)">
        <input type="radio" name="time" class="list-radio-check" value="1" v-model="setday"> 
        <span class="list-radio-circle"></span> 
        <em class="txt">今天</em>
      </label>
      <label @change="setTimes(2)">
        <input type="radio" name="time" class="list-radio-check" value="2" v-model="setday"> 
        <span class="list-radio-circle"></span> 
        <em class="txt">明天</em>
      </label>
      <label @change="setTimes(3)">
        <input type="radio" name="time" class="list-radio-check"value="3" v-model="setday"> 
        <span class="list-radio-circle"></span> 
        <em class="txt">后天</em>
      </label>
      <label @change="anotherTime">
        <input type="radio" name="time" class="list-radio-check" value="4" v-model="setday"> 
        <span class="list-radio-circle"></span> 
        <em class="txt">其他</em>
      </label>
    </div>

    <div class="form-wrap mb30">
      <div class="form-wrap-row">
        <div class="line displayflex">
          <div class="label">备注</div>
          <div class="ipt flex1">
            <textarea type="text" placeholder="请输入备注信息（最多200字符）" class="form-txtarea" v-model="memo" maxlength="200"></textarea>
          </div>
        </div>
      </div>
    </div>
    <!-- 单据类型 -->
    <mt-popup
      v-model="popupVisible"
      @click="popupVisible = false;"
      position="right" class="bill-popup">
      <ul class="bill-type">
        <template v-for="item in billType.list">
          <li @click="checkBill(item.value)">{{item.name}}</li>
        </template>
      </ul>
    </mt-popup>

    <div class="form-btn" @click="placeOrder">下单</div>
  </div>
</template>

<script>
import footerMenu from "@/commonComponent/footer.vue";
export default {
  name:'placeOrder',
  data() {
    return {
      visibility: false,
      value9:'',
      popupVisible:false,
      formDate: {
        choiceGoods: false,
        choiceQuick: false,
        arriveTime: '',
        list3: [],
        value3: [],
        customShow: true
      },
      seleAddr:{},
      Page: 0,
      Rows: 9999,
      checkItem:[],
      amount:0,
      customid:'',
      billno:"",
      billType:{
        list:[
          {
            'value': '04',
            'name': '药品'
          }, {
            'value': '01',
            'name': '普耗'
          }, {
              'value': '02',
              'name': '跟台高值'
          }, {
              'value': '03',
              'name': '备货高值'
          }, {
              'value': '05',
              'name': '后勤物资'
          }, {
              'value': '06',
              'name': '消毒用品'
          }, {
              'value': '07',
              'name': '洗涤用品'
          }, {
              'value': '08',
              'name': '中药材'
          }, {
              'value': '09',
              'name': '设施设备'
          }, {
              'value': '10',
              'name': '其他'
          }
        ],
        value:'',
        show:true
      },
      memo:'',
      quickAmount:0,
      setday:'',
      today:'',
    }
  },
  created() {
    this.getCusdata();
    this.getToday();
  },
  activated(){
    this.seleAddr = {};
    this.getGoods();
    if(this.formDate.choiceGoods){
      this.amountNum();
    };
    if(sessionStorage.memo && sessionStorage.memo != 'undefined'){
      this.memo = sessionStorage.memo;
    }else{
      this.memo = '';
    };
    if(this.formDate.value3[0]){
      this.getAddress();
    }
  }, 
  watch:{
    'formDate.value3'(){
      this.seleAddr = {};
      this.getAddress();
    },
    formDate: {
      handler(n,o) {
        let dt = n.arriveTime;
        if(dt !== ''){
          let curTime = new Date(),
              today = this.formatDT(curTime),
              tomorrow = this.formatDT(new Date(curTime.getTime()+24*60*60*1000)),
              aftertomorrow = this.formatDT(new Date(curTime.getTime()+2*24*60*60*1000));
          switch(dt){
            case today:
              this.setday = '1';
              break;
            case tomorrow:
              this.setday = '2';
              break;
            case aftertomorrow:
              this.setday = '3';
              break;
            default:
              this.setday = '4';
              break;
          }
        }
      },
      deep: true
    },
  },
  computed:{
    userinfo(){
      return localStorage.getItem('userinfo') === null?null:JSON.parse(localStorage.getItem('userinfo'));
    }
  },
  methods: {
    getToday() {
      var date = new Date(),
        year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate();
      if (month < 9) {
        month = "0" + month;
      }
      if (day < 9) {
        day = "0" + day;
      }
      var time = year + "-" + month + "-" + day;
      this.today = time;
    },
    anotherTime(){
      this.visibility=true;
    },
    setTimes(val){
      var curTime = new Date();
      var tomorrow = new Date(curTime.getTime()+24*60*60*1000);
      var aftertomorrow = new Date(curTime.getTime()+2*24*60*60*1000);    
      if(val == 1){
        //今天
        this.formDate.arriveTime = this.formatDT(curTime);
      }else if(val == 2){
        //明天
        this.formDate.arriveTime = this.formatDT(tomorrow);
      }else if(val == 3){
        //后天
        this.formDate.arriveTime = this.formatDT(aftertomorrow);
      }
    },
    noneCustoms(){
      this.Toast({
        message:'暂无客户，请先添加客户'
      })
      return false;
    },
    //获取是否有选中商品
    getGoods(){
      if(sessionStorage.goods){
        this.checkItem = JSON.parse(sessionStorage.goods)
      };
    },
    //获取地址
    getAddress() {
      var self = this;
      var userinfo = JSON.parse(localStorage.userinfo);
     
      var query = {
        CCGUID: self.formDate.value3[0],
        IsChecked:'Y'
      };
      this.Ajax.post('SearchCustomerAddress', query).then(function(resp) {
        if (resp.IsSuccess == true) {
          self.addlist = resp.Datas;
          for (var i = 0; i<self.addlist.length;i++) {
            if(self.addlist[i].IsChecked == 'Y'){
              self.seleAddr = self.addlist[i];
            }
          };
        }
        if (resp.Datas.length == 0) {
           self.seleAddr = {};
        }
      });
    },


    checkBill(value){
      this.billType.value = value;
      this.popupVisible = false;
      sessionStorage.removeItem('sechTxt');
      if(this.formDate.choiceQuick){
        this.$router.push({
          path: '/order/quick'
        });
      };
      if(this.formDate.choiceGoods){
        this.$router.push({
          path: '/order/placeChoice',
          query:{
            MedGuid:this.customid,
            billtype:value
          }
        });
      };
    },

    //选择下单方式
    choiceWay(way) {
      this.customid = this.formDate.value3[0];
      if(!this.customid || this.customid.length==0){
        this.Toast({
          message:'请先选择客户'
        })
        return false;
      }
      if (way > 0) {
        this.formDate.choiceQuick = false;
        this.formDate.choiceGoods = true;
      } else {
        this.formDate.choiceQuick = true;
        this.formDate.choiceGoods = false;
      };
      this.popupVisible = true;
    },
    //商品清单跳转
    choicedlist() {
      this.$router.push({
        path: '/order/placeChoiced'
      })
    },
    //收货地址跳转
    toAddress() {
      this.customid = this.formDate.value3[0];
      if(!this.customid || this.customid.length==0){
        this.Toast({
          message:'请先选择客户'
        })
        return false;
      }
      this.$router.push({
        path: '/order/address',
        query:{id: this.formDate.value3[0]}
      });
    },
    //获取客户列表
    getCusdata() {
      this.formDate.list3 = [];
      var self = this;
      var userinfo = JSON.parse(localStorage.userinfo);
      var query = {
        StaffID: userinfo.StaffID,
        HelpCode: '',
        Page: self.Page,
        Rows: self.Rows,
      };
      self.Ajax.post('SearchManagedHospital', query).then(function(resp) {
        if (resp.Datas.length > 0) {
          resp.Datas.forEach(function(element, index) {
            var ll = {
              name: element.Name,
              value: element.Guid,
            };
            self.formDate.list3.push(ll);
          }, this);
        }

      });
    },
    //总金额
    amountNum(){
      this.amount=0;
      for(var i=0;i<this.checkItem.length;i++){
        var price = this.checkItem[i].Price || 0;
        var qty = this.checkItem[i].PurchaserPoQty || 0;
        this.amount += price * parseInt(qty);
      }
    },
    //获取订单号
    creatBill(){
      var date = new Date();
      var Num = "";
      for (var i = 0; i < 6; i++) {
          Num += Math.floor(Math.random() * 10);
      }
      var month, curdate;
      if (date.getMonth() + 1 < 9) {
          month = '0' + (date.getMonth() + 1)
      } else {
          month = date.getMonth() + 1
      }
      if (date.getDate() < 9) {
          curdate = '0' + date.getDate()
      } else {
          curdate = date.getDate()
      };
      this.billno = 'DD' + date.getFullYear() + month + curdate + '0001' + Num;
    },
    //检验必填项
    checkForm(){
      this.customid = this.formDate.value3[0];
      if(!this.customid || this.customid.length==0){
        this.Toast({
          message:'请先选择客户'
        })
        return false;
      }
      if (!this.seleAddr.Address || this.seleAddr.length==0) {
        this.Toast({
          message:'请选择收货地址'
        })
        return false;
      }
      if(!this.formDate.choiceQuick && !this.formDate.choiceGoods){
        this.Toast({
          message:'请选择商品'
        })
        return false;
      }
      if(this.checkItem.length==0 && this.formDate.choiceGoods){
        this.Toast({
          message:'请选择商品'
        })
        return false;
      };
      if(this.formDate.choiceQuick){
        var imglist = sessionStorage.imglist,
            voicelist = sessionStorage.voicelist;
        if(!imglist && !voicelist && !this.memo){
          this.Toast({
            message:'请提交语音或者照片或者文本'
          })
          return false;
        };
      };
      if(!this.formDate.arriveTime){
        this.Toast({
          message:'请选择要求到货日期'
        })
        return false;
      }if(!this.billType.value){
        this.Toast({
          message:'请选择单据类型'
        })
        return false;
      };
      return true;
    },

    //reset数据
    resetDate(){
      //提交订单就把选中商品的缓存清空
      this.formDate.arriveTime = '';
      this.formDate.choiceGoods = false;
      this.formDate.choiceQuick = false;
      // this.formDate.value3= [];
      sessionStorage.clear();
      // this.getCusdata();
      this.formDate.list3 = [];
      this.billType.value= '';
      this.setday = '';
      this.memo = '';
      this.amount = 0;
      this.seleAddr = {};
      this.quickAmount = 0;
    },

    //点击提交
    placeOrder(){
      if(!this.checkForm()){
        return false;
      };
      //获取商户中文名称
      var medname = '';
      for(var i=0;i<this.formDate.list3.length;i++){
        if(this.formDate.list3[i].value == this.formDate.value3){
          medname = this.formDate.list3[i].name;
        }
      };
      var self = this;
      var info = JSON.parse(localStorage.userinfo);
          this.creatBill();
      var query = {
          BillNo: this.billno,
          TenantGuid: info.TenantGuid,
          CorpGuid: info.CorpGuid,
          MedName: medname,
          BillType: this.billType.value,
          SupplierName: info.CorpName,
          MedGuid: this.formDate.value3[0],
          MedDeptName: '',//要货科室
          MedStoreName: '',//要货库房
          PlanEndDate: this.formDate.arriveTime,
          Province: this.seleAddr.Province,
          City: this.seleAddr.City,
          District: this.seleAddr.District,
          CountSum: this.formDate.choiceQuick ? 0 : this.checkItem.length,
          Address: this.seleAddr.Address,
          BuyerGUID: info.StaffID,
          BuyerName: info.Name,
          CreateUserId: info.StaffID,
          UpdateUserId: info.StaffID,
          UpdateUserName: info.Name,
          CreateUserName: info.Name,
          Venue: $("#address").html(),
          Memo: this.memo
      };
      if(this.formDate.choiceQuick){
        query.imglist = sessionStorage.imglist?JSON.parse(sessionStorage.imglist):'';
        query.Voice = sessionStorage.voicelist;
        query.voiceListBase64 = sessionStorage.voiceListBase64;
        query.DetailSum = this.quickAmount;//总金额
      }else{
        query.imglist =null;
        query.Voice = null;
        query.voiceListBase64 = null;
        query.orderdeail = this.checkItem;
        query.DetailSum = this.amount;//总金额
      };
      this.Ajax.post('OrderEntry', query).then(function(resp) {
        if (resp.IsSuccess) {
          self.resetDate();
          self.MessageBox.alert('下单成功').then(action => {
            self.$router.push({
              path: '/order/acceptList'
            })
          });
        } else {
          self.Toast({
              message: resp.ErrorMessage || '操作失败'
          });
        }
      });
    },

    //------
    formatDT(val){
      var year = val.getFullYear(),
          month = val.getMonth()+1,
          day = val.getDate();
      if(month<10){
        month = '0' + month;
      }
      if(day<10){
        day = '0' + day;
      }
      return year + '-' + month + '-' + day;
    }
  }
}
</script>